package com.sgq.vue.service.picture.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgq.vue.dao.picture.PictureMapper;
import com.sgq.vue.dao.picture.TagMapper;
import com.sgq.vue.entity.picture.Picture;
import com.sgq.vue.entity.picture.Tag;
import com.sgq.vue.service.picture.TagService;
import com.sgq.vue.vo.query.picture.TagQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author: 83778
 * @date: 2024-01-05 19:59
 * @desc:
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag>implements TagService {

    @Autowired
    private PictureMapper pictureMapper ;

    @Override
    public IPage findTagByPage(TagQueryVo tagQueryVo) {
        Long pageNo = tagQueryVo.getPageNo();
        Long pageSize = tagQueryVo.getPageSize();
        IPage<Tag> tagPage = new Page<>(pageNo,pageSize);
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(tagQueryVo.getName()),Tag::getName,tagQueryVo.getName());
        IPage<Tag> page = this.baseMapper.selectPage(tagPage, queryWrapper);
        return page;
    }

    @Override
    public List<Tag> findTagByCreatorId(Long userId) {
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Tag::getCreateBy,userId);
        List<Tag> tags = this.baseMapper.selectList(queryWrapper);
        return tags;
    }

    @Override
    public boolean check(Long tagId) {
        List<Picture> pictures = pictureMapper.selectList(new QueryWrapper<Picture>());
        AtomicBoolean hasBeenUsed = new AtomicBoolean(false);
        pictures.stream().map(Picture::getTags).forEach(tags ->{
             if (Arrays.asList(tags.split(",")).contains(tagId.toString())){
                 hasBeenUsed.set(true);
                 return ;
             }
        });
        return hasBeenUsed.get();
    }
}
